package cn.skyclass.events
{
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.utils.Dictionary;
	import flash.utils.getQualifiedClassName;
	
	/**
	 * 提供全局事件通知模型，同时管理多个通知实例
	 */
	public class EventNotification extends EventDispatcher
	{
		public function EventNotification(singletonEnforcer:SingletonEnforcer){}
		
		/**
		 * 默认的实例名称，当不提供名称或是名称不合法时将使用此名称
		 */
		public static const DEFAULT_INSTANCE_NAME:String = "default";
		
		/**
		 * 存储多个事件通知实例的字典
		 */
		private static var instanceDic:Dictionary = new Dictionary();
		
		/**
		 * 当前实例的名称
		 */
		public var instanceName:String;
		
		
		/**
		 * 根据提供的名称字符串或是相应的事件类型来获取其对应的通知实例
		 * eg1: EventNotification.getInstance("CustomEventName1");
		 * eg1: EventNotification.getInstance(CustomEvent);
		 */
		public static function getInstance(strNameOrEventClass:Object="default"):EventNotification{
			// 获取实例的名称
			var instanceName:String = "default";
			if(strNameOrEventClass is String){
				instanceName = String(strNameOrEventClass);
			}else if(strNameOrEventClass is Class){
				instanceName = getQualifiedClassName(strNameOrEventClass);
			}
			
			// 根据实例名称从字典中查找实例，如果未找到，则新建一个实例并加入字典中并返回此实例
			var instance:EventNotification = instanceDic[instanceName];
			if(instance == null){
				instance = new EventNotification(new SingletonEnforcer());
				instance.instanceName = instanceName;
				instanceDic[instanceName] = instance;
			}
			return instance;
		}
		
		override public function dispatchEvent(event:Event):Boolean{
			try{
				return super.dispatchEvent(event);
			}catch(err:Error){
				trace(err);
			}
			return true;
		}
		
	}
}

// just can access this class in this file
class SingletonEnforcer {}

